import 'package:get/get.dart';
import '../model/comment_model.dart';
import '../data/comment_data.dart';

/// 评论状态管理
/// 使用GetX进行全局状态管理，采用非常规命名避免标准模式
class CommentState extends GetxController {
  // 所有评论
  final RxList<CommentModel> _allComments = <CommentModel>[].obs;

  // 当前用户ID
  final RxString _currentUserId = ''.obs;

  // 用户点赞的评论ID集合
  final RxSet<String> _userLikedComments = <String>{}.obs;

  // 用户点踩的评论ID集合
  final RxSet<String> _userDislikedComments = <String>{}.obs;

  /// 获取所有评论
  List<CommentModel> get allComments => _allComments.toList();

  /// 获取当前用户ID
  String get currentUserId => _currentUserId.value;

  /// 设置当前用户ID
  void setCurrentUserId(String userId) {
    _currentUserId.value = userId;
  }

  /// 添加评论
  void addComment(CommentModel comment) {
    if (comment.isValid) {
      _allComments.add(comment);
      // 按时间排序（最新的在前面）
      _allComments.sort((a, b) => b.commentTime.compareTo(a.commentTime));
    }
  }

  /// 添加帖子评论
  void addPostComment(String postId, String content) {
    final comment = CommentModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      userId: _currentUserId.value,
      postId: postId,
      content: content,
      commentTime: DateTime.now(),
    );
    addComment(comment);
  }

  /// 更新评论
  void updateComment(CommentModel updatedComment) {
    final index = _allComments.indexWhere(
      (comment) => comment.id == updatedComment.id,
    );
    if (index != -1 && updatedComment.isValid) {
      _allComments[index] = updatedComment;
      // 重新排序
      _allComments.sort((a, b) => b.commentTime.compareTo(a.commentTime));
    }
  }

  /// 删除评论
  void deleteComment(String commentId) {
    _allComments.removeWhere((comment) => comment.id == commentId);
  }

  /// 获取帖子的所有评论
  List<CommentModel> getPostComments(String postId) {
    return _allComments.where((comment) => comment.postId == postId).toList()
      ..sort((a, b) => b.commentTime.compareTo(a.commentTime));
  }

  /// 获取用户的所有评论
  List<CommentModel> getUserComments(String userId) {
    return _allComments.where((comment) => comment.userId == userId).toList()
      ..sort((a, b) => b.commentTime.compareTo(a.commentTime));
  }

  /// 获取帖子的评论数量
  int getPostCommentCount(String postId) {
    return _allComments.where((comment) => comment.postId == postId).length;
  }

  /// 点赞评论
  void likeComment(String commentId) {
    final index = _allComments.indexWhere((comment) => comment.id == commentId);
    if (index != -1) {
      final comment = _allComments[index];

      // 如果用户已经点赞，则取消点赞
      if (_userLikedComments.contains(commentId)) {
        _userLikedComments.remove(commentId);
        _allComments[index] = comment.copyWith(
          likeCount: comment.likeCount > 0 ? comment.likeCount - 1 : 0,
        );
      } else {
        // 如果用户已经点踩，先取消点踩
        if (_userDislikedComments.contains(commentId)) {
          _userDislikedComments.remove(commentId);
          _allComments[index] = comment.copyWith(
            dislikeCount:
                comment.dislikeCount > 0 ? comment.dislikeCount - 1 : 0,
            likeCount: comment.likeCount + 1,
          );
        } else {
          // 新增点赞
          _allComments[index] = comment.copyWith(
            likeCount: comment.likeCount + 1,
          );
        }
        _userLikedComments.add(commentId);
      }
    }
  }

  /// 取消点赞评论
  void unlikeComment(String commentId) {
    final index = _allComments.indexWhere((comment) => comment.id == commentId);
    if (index != -1 && _userLikedComments.contains(commentId)) {
      final comment = _allComments[index];
      _userLikedComments.remove(commentId);
      _allComments[index] = comment.copyWith(
        likeCount: comment.likeCount > 0 ? comment.likeCount - 1 : 0,
      );
    }
  }

  /// 点踩评论
  void dislikeComment(String commentId) {
    final index = _allComments.indexWhere((comment) => comment.id == commentId);
    if (index != -1) {
      final comment = _allComments[index];

      // 如果用户已经点踩，则取消点踩
      if (_userDislikedComments.contains(commentId)) {
        _userDislikedComments.remove(commentId);
        _allComments[index] = comment.copyWith(
          dislikeCount: comment.dislikeCount > 0 ? comment.dislikeCount - 1 : 0,
        );
      } else {
        // 如果用户已经点赞，先取消点赞
        if (_userLikedComments.contains(commentId)) {
          _userLikedComments.remove(commentId);
          _allComments[index] = comment.copyWith(
            likeCount: comment.likeCount > 0 ? comment.likeCount - 1 : 0,
            dislikeCount: comment.dislikeCount + 1,
          );
        } else {
          // 新增点踩
          _allComments[index] = comment.copyWith(
            dislikeCount: comment.dislikeCount + 1,
          );
        }
        _userDislikedComments.add(commentId);
      }
    }
  }

  /// 取消点踩评论
  void undislikeComment(String commentId) {
    final index = _allComments.indexWhere((comment) => comment.id == commentId);
    if (index != -1 && _userDislikedComments.contains(commentId)) {
      final comment = _allComments[index];
      _userDislikedComments.remove(commentId);
      _allComments[index] = comment.copyWith(
        dislikeCount: comment.dislikeCount > 0 ? comment.dislikeCount - 1 : 0,
      );
    }
  }

  /// 获取评论的点赞数量
  int getCommentLikeCount(String commentId) {
    final comment = _allComments.firstWhereOrNull((c) => c.id == commentId);
    return comment?.likeCount ?? 0;
  }

  /// 获取评论的点踩数量
  int getCommentDislikeCount(String commentId) {
    final comment = _allComments.firstWhereOrNull((c) => c.id == commentId);
    return comment?.dislikeCount ?? 0;
  }

  /// 检查用户是否点赞了评论
  bool isCommentLikedByUser(String commentId) {
    return _userLikedComments.contains(commentId);
  }

  /// 检查用户是否点踩了评论
  bool isCommentDislikedByUser(String commentId) {
    return _userDislikedComments.contains(commentId);
  }

  /// 根据ID获取评论
  CommentModel? getCommentById(String commentId) {
    try {
      return _allComments.firstWhere((comment) => comment.id == commentId);
    } catch (e) {
      return null;
    }
  }

  /// 创建新评论实例
  CommentModel createNewComment({
    required String postId,
    required String content,
  }) {
    return CommentModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      userId: _currentUserId.value,
      postId: postId,
      content: content,
      commentTime: DateTime.now(),
    );
  }

  /// 获取评论统计信息
  Map<String, int> getCommentStatistics() {
    final stats = <String, int>{};

    // 总评论数
    stats['totalComments'] = _allComments.length;

    // 当前用户评论数
    stats['currentUserComments'] =
        _allComments
            .where((comment) => comment.userId == _currentUserId.value)
            .length;

    return stats;
  }

  /// 清空所有评论
  void clearAllComments() {
    _allComments.clear();
  }

  /// 删除帖子的所有评论
  void deletePostComments(String postId) {
    _allComments.removeWhere((comment) => comment.postId == postId);
  }

  @override
  void onInit() {
    super.onInit();
    _loadDefaultData();
  }

  /// 加载默认数据
  void _loadDefaultData() {
    _allComments.assignAll(CommentData.getDefaultComments());
  }
}
